package com.tedu.springboot22102.controller;

import com.tedu.springboot22102.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 该类处理和用户相关的操作
 */
@Controller
public class UserController {
    /**
     * 保存所有用户信息的目录
     */
    private static File userDir;

    /**
     静态块，只创建一次
     */
    static {
        userDir = new File("./users");
        if (!userDir.exists()) {//目录不存在则直接创建
            userDir.mkdir();
        }
    }

    /**
     * 用户注册
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("开始处理注册！");
        /*
        HttpServletRequest对象表示请求，（浏览器发过来的信息都保存在这个对象中，当我们想获取
        提交过来的参数时，可以调用请求对象的方法）
        request.getParameter

        获取参数有两种情况:
        1.用户在输入框没有输出信息，返回空串
        2.浏览器没有提交该参数，返回值为null
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username + " " + password + " " + nickname + " " + ageStr);

       /*
       验证工作
        */
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty() ||
                nickname == null || nickname.trim().isEmpty() ||
                ageStr == null || ageStr.trim().isEmpty() ||
                !ageStr.matches("[0-9]+")) {
            try {
                response.sendRedirect("/reg_err.html");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //将字符串age转换成int型
        int age = Integer.parseInt(ageStr);
        //创建user对象
        User user = new User(username, password, nickname, age);
        //创建文件，以username.obj为名称，存放在userDir文件夹中
        File file = new File(userDir, username + ".obj");
        //验证用户是否已经存在
        if (file.exists()) {
            try {
                response.sendRedirect("/exit_user.html");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //创建序列化流程------字节流连接序列化流
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos);) {
            oos.writeObject(user);//将注册用户序列化到文件中保存
            response.sendRedirect("/regsuccess.html");//注册成功后，返回注册成功界面
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 验证用户信息
     *
     * @param request
     * @param response
     */
    @RequestMapping("/Login")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("验证用户登录信息");
        String loginname = request.getParameter("loginname");
        String passwordname = request.getParameter("loginpassword");

//        File file1 = new File(userDir,loginname+".obj");
//        if (!file1.exists()){
//            try {
//                response.sendRedirect("loginnoexit");
//                return;
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }


//        File dir = new File("./users");
//        if(dir.isDirectory()){
//            File[] list = dir.listFiles();
//            for(File lists : list){
        File file1 = new File(userDir, loginname + ".obj");
        if (file1.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file1);
                ObjectInputStream oir = new ObjectInputStream(fis);
                Object obj = oir.readObject();
                User u = (User) obj;
                if (passwordname.equals(u.getPassword()) && loginname.equals(u.getUsername())) {
                    response.sendRedirect("/loginsucess.html");
                } else if (!passwordname.equals(u.getPassword()) || !loginname.equals(u.getUsername())) {
                    response.sendRedirect("/loginerr.html");
                }
                oir.close();
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                response.sendRedirect("/loginnoexit.html");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 动态信息
     * @param request
     * @param response
     */
    @RequestMapping("/userlist")
    public void userList(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始动态页面");
        List<User> userList = new ArrayList<>();
        File[] subs = userDir.listFiles(f -> f.getName().endsWith(".obj"));
        for (File sub : subs) {
            try (
                    FileInputStream fis = new FileInputStream(sub);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User) ois.readObject();//反序列化每个注册用户
                userList.add(user);//将该注册用户信息存入集合备用
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<html>");
            pw.println("<head>");
            pw.println("<meta charset='utf-8'>");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border='1'>");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("</tr>");
            for (User user : userList) {
                pw.println("<tr>");
                pw.println("<td>" + user.getUsername() + "</td>");
                pw.println("<td>" + user.getPassword() + "</td>");
                pw.println("<td>" + user.getNickname() + "</td>");
                pw.println("<td>" + user.getAge() + "</td>");
                pw.println("</tr>");
            }
            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


